package com.yungu.swift.schedule.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.schedule.config.QuartzManager;
import com.yungu.swift.schedule.config.model.ScheduleJob;
import com.yungu.swift.schedule.job.ActivityQuartzActiveJob;
import com.yungu.swift.system.marketing.model.dto.MarketingActivityDto;
import com.yungu.swift.system.marketing.service.MarketingActivityService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import static com.yungu.swift.schedule.config.NacosListener.SYS_CONFIG;


/**
 * 活动管理的定时器管理服务类
 * Created by cuixiuyin on 2017/8/16.
 */
@Service
public class MarketingActivityQuartzService {

    private static final Logger logger = LoggerFactory.getLogger(MarketingActivityQuartzService.class);

    @Reference
    private MarketingActivityService marketingActivityService;

    @Autowired
    private QuartzManager quartzManager;

    public void activityQuartz() {
        logger.info("‘预约开启的活动’统计开始");
        // 查询所有需要预约开启的活动
        ResponseData<List<MarketingActivityDto>> activityQuartz = marketingActivityService.activityQuartz(SYS_CONFIG.getAppid());
        if (activityQuartz.isSuccess() && CollectionUtils.isNotEmpty(activityQuartz.getData())) {
            for (final MarketingActivityDto marketingActivityDto : activityQuartz.getData()) {
                ScheduleJob scheduleJob = new ScheduleJob();
                scheduleJob.setJobId(marketingActivityDto.getUuid());
                scheduleJob.setJobName(marketingActivityDto.getUuid());
                scheduleJob.setJobGroup(marketingActivityDto.getUuid());
                scheduleJob.setJobStatus("1");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("ss mm HH dd MM ? yyyy");
                String cron = simpleDateFormat.format(marketingActivityDto.getPutInDateOn());
                scheduleJob.setCronExpression(cron);
                quartzManager.addJob(scheduleJob, ActivityQuartzActiveJob.class);
                logger.info("活动管理定时预约添加任务成功，uuid：{}", marketingActivityDto.getUuid());
                // 活动置为已添加
                CompletableFuture.runAsync(() -> {
                    MarketingActivityDto editParam = new MarketingActivityDto();
                    editParam.setUuid(marketingActivityDto.getUuid());
                    editParam.setVersion(1);
                    marketingActivityService.edit(editParam);
                });
            }

        }
    }
}
